package org.krams.tutorial.service.dao.hibernate;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.krams.tutorial.service.dao.MoneyDao;
import org.krams.tutorial.service.model.Money;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

/**
 * User: volyn
 * Date: 07.04.12
 * Time: 16:09
 */
@Repository("moneyDao")
public class MoneyDaoHibernate implements MoneyDao {

    private HibernateTemplate hibernateTemplate;
    private SessionFactory sessionFactory;

    public HibernateTemplate getHibernateTemplate() {
        return hibernateTemplate;
    }

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
        this.hibernateTemplate = new HibernateTemplate(sessionFactory);
    }

    public List<Money> findAll() {
        return getHibernateTemplate().loadAll(Money.class);
    }

    @Override
    public double getBalance() {
       return getHibernateTemplate().execute(new HibernateCallback<Double>() {
            @Override
            public Double doInHibernate(Session session) throws HibernateException, SQLException {
                Criteria criteria = session.createCriteria(Money.class);
                criteria.setProjection(Projections.sum("amount"));
                if(criteria.list().get(0) == null){
                    return 0D;
                }
                return (Double)criteria.list().get(0);
            }
        });
    }

    @Override
    public void save(Money money) {
        getHibernateTemplate().save(money);
    }

    @Override
    public void removeAll() {
        getHibernateTemplate().deleteAll(findAll());
    }
}
